import {
  addFuncApi,
  delFuncApi,
  editFuncApi,
  getUserMenuApi
} from '@/api/system/menu'
import { treeForEach } from '@/utils/tree'
import { Ref } from 'vue'
import { FuncTypeEnum } from '../enum'

type props = {
  handleType: Ref<'add' | 'edit' | ''>
  handleTag: Ref<string>
  funcTree: Ref<any>
  model: Ref<any>
}

export const useFuncApi = ({
  handleType,
  handleTag,
  funcTree,
  model
}: props) => {
  const confirmLoading = ref(false)
  // 获取数据
  const fetchFuncTree = async () => {
    try {
      const res = await getUserMenuApi({ isAllMenu: true })
      if (res.code === '0000') {
        treeForEach(res.data as Array<any>, (item) => {
          if (!item.children?.length) {
            item.children = null
          }
        })
        funcTree.value = res.data
        return {
          data: res.data
        }
      }
    } catch (e) {
      console.log(e)
    }
  }

  // 新增修改资源请求
  const fetchAddOrEditFunc = async (db: () => void) => {
    try {
      confirmLoading.value = true
      const fetch = handleType.value === 'add' ? addFuncApi : editFuncApi

      if (handleType.value === 'add') {
        if (model.value.funcType === FuncTypeEnum.directory) {
          model.value.parentId = 0
          model.value.compPath = 'layout'
        }

        if (model.value.funcType === FuncTypeEnum.button) {
          model.value.url = 'button'
        }
      }
      const data = {
        ...model.value
      }
      if (data.__displayValue__) delete data.__displayValue__
      const res = await fetch(data)
      if (res.code === '0000') {
        window['$message'].success(handleTag.value + '成功')
        db()
      }
    } catch (e) {
      console.log(e)
    } finally {
      confirmLoading.value = false
    }
  }

  const fetchDelFunc = async (id, db: () => void) => {
    try {
      const res = await delFuncApi({ id })
      if (res.code === '0000') {
        window['$message'].success('删除成功')
        db()
      }
    } catch (e) {
      console.log(e)
    }
  }

  return {
    fetchFuncTree,
    fetchAddOrEditFunc,
    fetchDelFunc,
    confirmLoading
  }
}
